package org.example3;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *      InputStream inputStream = socket.getInputStream(); // 这里不阻塞
 *      inputStream.read() 这里阻塞
 */

public class ServerStream {

    //    static Person sendObj = new Person("严金玉");
    static String sendObj = "我是服务端,1234Abc";

    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("---------------服务器准备好了------------------");

        Socket accept = serverSocket.accept();
        InputStream inputStream = accept.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[555];
        int len = 0;
        while ((len = inputStream.read(bytes)) != -1) {
            System.out.println("-------------进入循环了");
            baos.write(bytes, 0, len);
            baos.flush();
//            String s = new String(bytes, 0, len);
//            System.out.println(   "str  is "+s);
            Object object = SerializerUtil.deserialize2Object(bytes, 0, len);
            System.out.println("object is " + object);
            System.out.println(   "len  is "+len);
        }

        System.out.println("-------------出循环了");
        Object result = SerializerUtil.deserialize2Object(baos.toByteArray());
        String hostAddress = accept.getInetAddress().getHostAddress();
        System.out.println(hostAddress + "发来了信息:" + result);

        OutputStream outputStream = accept.getOutputStream();
        byte[] bytes1 = SerializerUtil.serialize2ByteArray(sendObj);
        outputStream.write(bytes1);
        System.out.println("发送客户端已完成");

//        accept.close();

        while (true) {

        }
    }
}
